package com.CST.websocket;


import com.CST.common.constant.*;
import com.CST.config.service.*;
import com.CST.config.service.impl.*;
import com.CST.vo.*;
import java.io.*;
import java.util.*;
import org.slf4j.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.web.socket.*;


@Service
public class SocketHandler implements WebSocketHandler {

    private static final Logger logger;
    private static final ArrayList<WebSocketSession> users;
    @Autowired
    private RedisServiceImpl redisService;
    @Autowired
    @Lazy
    private IRemindRecordService remindRecordService;

    static {
	  users = new ArrayList<WebSocketSession>();
	  logger = LoggerFactory.getLogger(SocketHandler.class);
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
	  logger.info("建立连接socket");
	  users.add(webSocketSession);
	  final boolean exists = redisService.exists(RedisConstant.wsLoginUser);
	  if (exists) {
		String username = redisService.get(RedisConstant.wsLoginUser).toString();
		if (username != null) {
		    Integer msgSumByUserId = remindRecordService.getMsgSumByUserId(username);
		    webSocketSession.sendMessage(new TextMessage(String.valueOf(msgSumByUserId)));
		}
	  }
    }

    @Override
    public void handleMessage(WebSocketSession webSocketSession,
					WebSocketMessage<?> webSocketMessage) throws Exception {

    }

    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable)
	  throws Exception {
	  if (webSocketSession.isOpen()) {
		webSocketSession.close();
	  }
	  users.remove(webSocketSession);

    }

    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus)
	  throws Exception {
	  logger.debug("关闭连接");
	  users.remove(webSocketSession);
    }

    @Override
    public boolean supportsPartialMessages() {
	  return false;
    }

    /**
     * 群发消息
     *
     * @param message
     */
    public void sendMessageToUsers(TextMessage message) {
	  System.out.println("群发消息");
	  for (WebSocketSession user : users) {
		//System.out.println(user.getAttributes().get("user"));
		try {
		    if (user.isOpen()) {
			  user.sendMessage(message);
		    }
		} catch (IOException e) {
		    e.printStackTrace();
		}
	  }
    }

    /**
     * 单个用户发消息
     *
     * @param userName
     * @param message
     */
    public void sendMessageToUser(String userName, TextMessage message) {
	  for (WebSocketSession user : users) {
		if (user.getAttributes().get("user").equals(userName)) {
		    try {
			  if (user.isOpen()) {
				user.sendMessage(message);
			  }
		    } catch (IOException e) {
			  e.printStackTrace();
		    }
		    //break;
		}
	  }
    }


    /**
     * 指定给多个用户发消息
     *
     * @param userName
     * @param message
     */
    public void sendMessageToUserList(List<String> userName, TextMessage message) {

	  for (WebSocketSession user : users) {

		if (userName.contains(user.getAttributes().get("user"))) {
		    try {
			  if (user.isOpen()) {
				user.sendMessage(message);
			  }
		    } catch (IOException e) {
			  e.printStackTrace();
		    }
		    //break;
		}
	  }
    }


    /**
     * 指定给多个用户发消息
     */
    public void sendMessageToUserLists(List<RemindCountResponse> messageCountRes) {

	  for (WebSocketSession user : users) {
		for (RemindCountResponse remindCountResponse : messageCountRes) {
		    if (remindCountResponse.getUserName().equals(user.getAttributes().get("user"))) {
			  try {
				if (user.isOpen()) {
				    String msg = remindCountResponse.getMsgCount();
				    //发消息
				    user.sendMessage(new TextMessage(msg));
				}
			  } catch (IOException e) {
				e.printStackTrace();
			  }
			  break;
		    }
		}

	  }
    }

}
